package com.hao.nettyrpc.code;

import com.hao.nettyrpc.serializer.CommonSerializer;
import com.hao.nettyrpc.enums.PackageType;
import com.hao.nettyrpc.entity.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/4/11 13:03
 */
public class CommonEncoder extends MessageToByteEncoder {
    private static final int MAGIC_NUMBER = 0xCAFEBABE;
    private final CommonSerializer serializer;

    public CommonEncoder(CommonSerializer serializer) {
        this.serializer = serializer;
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        byteBuf.writeInt(MAGIC_NUMBER); //魔数
        if (o instanceof RpcRequest) { //消息类型
            byteBuf.writeInt(PackageType.REQUEST_PACK.getCode());
        }else {
            byteBuf.writeInt(PackageType.RESPONSE_PACK.getCode());
        }
        byteBuf.writeInt(serializer.getCode());//序列化方法
        byte[] bytes = serializer.serialize(o);//序列化
        byteBuf.writeInt(bytes.length);//bytes长度
        byteBuf.writeBytes(bytes);//内容
    }
}
